<?php declare(strict_types=1);

namespace Distributed\Event;

use Distributed\Contract\IEvent;
use Communication\TxSocketData;
use Distributed\Group\TransGroupManage;
use Distributed\Constant;
use UntilDistributed\Log;
use Exception;
use Distributed\Group\TransactionManage;

/**
 * 预提交
 * @author mg
 *
 */
class ActionPreCommit extends AbstractEvent implements IEvent
{
	/**
	 *
	 * {@inheritDoc}
	 * @see \Distributed\Contract\IEvent::parseEvent()
	 */
	public function parseEvent(int $fd): ?TxSocketData
	{
		$groupId = $this->data->transGroup->groupId;
		
		$socketData = & $this->data;
		
		//更新redis状态为cancommit
		TransGroupManage::getInstance()->updateItemStatus($groupId, $socketData->transaction, Constant::$tx_status_cancommit);
		TransGroupManage::getInstance()->updateGroupStatus($groupId, Constant::$tx_status_cancommit);
		
		Log::getInstance()->info("txmanage precommit start");
		//查找事务组信息
		$transactionList = TransGroupManage::getInstance()->getItemsByGroupId($groupId);
		
		if(empty($transactionList))
		{
			
			Log::getInstance()->error("commit cancel: have no transaction actor");
			
			return TxSocketData::createResponse(Constant::$tx_complete_fail);
		}
		try
		{
			$socketData->result = Constant::$tx_complete_ok;
			
			$transactionList = TransactionManage::getInstance()->precommit($socketData, $fd);
		}
		catch(Exception $e)
		{
			dump($e->getMessage());
			Log::getInstance()->error($e->getMessage().'---'.__FILE__.'---'.__LINE__);
			//通知发起者回滚
			return TxSocketData::createResponse(Constant::$tx_complete_fail);
			
		}
		Log::getInstance()->info("txmanage precommit end");
		
		return  TxSocketData::createResponse(Constant::$tx_complete_ok);
	}
}